﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ncwebapi.Model;

namespace ncwebapi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly ILogger<UserController> _logger;

        private readonly IWebHostEnvironment _env;

        public UserController(ILogger<UserController> logger, IWebHostEnvironment env)
        {
            _logger = logger;
            _env = env;
        }

        [NonAction]
        public void say() { }

        [HttpPost]
        public async Task<ActionResult<List<string>>> index() {
            _logger.LogInformation("index 方法");
            var list = new List<string>();
            list.Add("aaa");
            list.Add("bbb");
            return Ok(list);
        }

        [HttpPost]
        public ActionResult login([FromForm] User user) {
            _logger.LogInformation("登录方法");
            return Ok(user);
        }

        [HttpPost]
        public async Task<IActionResult> OnPostUploadAsync(List<IFormFile> files) {
            _logger.LogWarning(_env.WebRootPath);
            long size = files.Sum(f => f.Length);
            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    var filePath = Path.Combine(_env.WebRootPath, "images", formFile.FileName);

                    _logger.LogWarning(filePath);

                    using (var stream = System.IO.File.Create(filePath))
                    {
                        await formFile.CopyToAsync(stream);
                    }
                }
            }
            return Ok(new { count = files.Count, size }) ;
        }
    }
}
